import { ProForm, ProFormText } from "@ant-design/pro-components"
import { request, useRequest,history } from "@umijs/max"
import { Button, message, Tabs } from "antd"

const Login = () => {
    const {run:login,loading:loginLoading} = useRequest(async (values) => {
        return request(`/api/user/${values.userName}`, {
            method: 'get',
        })
    }, {
        manual: true,
        onSuccess: (res) => {
            if(!res) {
                message.error('用户名或密码错误')
                return
            }
            const user = {userName: res.userName, password: res.password,id: res.id}
            
            localStorage.setItem('user', JSON.stringify(user))

            history.push('/')
        }
    })

    const {run:register,loading:registerLoading} = useRequest(async (values) => {
        return request('/api/user', {
            method: 'POST',
            data: values
        })
    }, {
        manual: true,
        onSuccess: (res) => {
            if(!res) {
                message.error('用户已存在')
                return
            }
            const user = {userName: res.userName, password: res.password,id: res.id}
            
            localStorage.setItem('user', JSON.stringify(user))

            history.push('/')
        }
    })

    return <Tabs>
        <Tabs.TabPane tab="登录" key="1">
            <ProForm submitter={false} onFinish={values => login(values)}>
                <ProFormText name="userName" label="用户名" rules={[{required: true,message: '请输入用户名'}]} />
                <ProFormText name="password" label="密码" rules={[{required: true,message: '请输入密码'}]} />
                <Button type="primary" htmlType="submit">登录</Button>
            </ProForm>
        </Tabs.TabPane>
        <Tabs.TabPane tab="注册" key="2">
            <ProForm submitter={false} onFinish={values => register(values)}>
                <ProFormText name="userName" label="用户名" rules={[{required: true,message: '请输入用户名'}]} />
                <ProFormText name="password" label="密码" rules={[{required: true,message: '请输入密码'}]} />
                <Button type="primary" htmlType="submit">注册</Button>
            </ProForm>
        </Tabs.TabPane>
    </Tabs>
}

export default Login